package adv.i31.robot;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.charset.Charset;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import com.google.common.base.Ascii;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.google.common.io.InputSupplier;

import android.content.Context;
import android.content.res.AssetManager;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView.Renderer;
import android.util.Xml.Encoding;

public class MyRenderer implements Renderer {

	Robot mRobot;

	public void setClearColor(float r, float g, float b) {
		this.r = r;
		this.b = b;
		this.g = g;
	}

	private float r = 0.0f, b = 0.0f, g = 0.0f;

	public void onDrawFrame(GL10 gl) {
		GLES20.glClearColor(r, g, b, 1.0f);

		GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);

		mRobot.draw(mProgram, mCamera);

	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		mCamera.onSurfaceChanged(width, height);
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		GLES20.glClearColor(0.1f, 0, 0, 1.0f);
		System.out.println("Surface created");

		// compile shaders only the first time a surface is created
		if (mProgram == null) {
			mProgram = new Program(new VertexShader(vertexShaderCode), new FragmentShader(
					fragmentShaderCode));

			// use this program for rendering
			mProgram.use();
		}
	}

	public MyRenderer() {
		System.out.println("New renderer");
		mCamera = new Camera();
		mRobot = new Robot();

	}

	public void loadShaders(Context context) throws IOException {
		// load the shaders from assets
		AssetManager am = context.getAssets();

		InputStream is;

		is = am.open("shaders/program.fsh", AssetManager.ACCESS_BUFFER);
		fragmentShaderCode = CharStreams.toString(new InputStreamReader(is));

		is = am.open("shaders/program.vsh", AssetManager.ACCESS_BUFFER);
		vertexShaderCode = CharStreams.toString(new InputStreamReader(is));
	}

	String vertexShaderCode;
	String fragmentShaderCode;

	private Camera mCamera;

	private Program mProgram;

}